package sd.settemmezzo.player;

import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.text.ParseException;

import javax.swing.SwingUtilities;

import sd.settemmezzo.common.PlayerInterface;
import sd.settemmezzo.common.Registration;
import sd.settemmezzo.graphic.UI_Input;

import sd.settemmezzo.player.state.LocalState;

public class PlayerClient {

	private static String RMI_SERVER;
	private static int RMI_PORT;	
	private String clientName;
	
	public void start(String name, String Server, int Port) {

		RMI_SERVER = Server;
		RMI_PORT = Port;
		clientName = name;
		
		SwingUtilities.invokeLater(new Runnable() {
            public void run() {
				LocalState localState = LocalState.getInstance();
				try {
					Registry registry = LocateRegistry.getRegistry(RMI_SERVER, RMI_PORT);
					Registration registration = (Registration) registry.lookup("Registration");
		
					PlayerInterface playerInterface = (PlayerInterface) new PlayerImplement(clientName);
					
					// returns id if success, -1 otherwise
					int result = registration.register(playerInterface, clientName);
		
					if (result > 0) {
		
						localState.setId(result);
						localState.setName(clientName);
		
					} else {
		
						System.err.println("Registration failed: name " + clientName + " in use...");
						
					}
					System.out.println("My ID = " + result);
		
				} catch (Exception e) {
					System.err.println("Player exception:");
					e.printStackTrace();
				}
            }
		});

	}

	public static void main(String[] args) throws RemoteException, UnknownHostException, ParseException {
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}

		SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	UI_Input input;
				try {
					input = new UI_Input();
					input.setVisible(true);
				} catch (ParseException e) {
					e.printStackTrace();
				}
            }
        });
       
        
	}
}